简体   繁体   中英

Staring to learn Flutter. Wondering how to import a class into a stateful widget

I've just started to learn flutter and am trying to make a ToDo list app. If you see the code below, I was wondering how I can move the code below class _TodoListState extends State<TodoList> { and before Widget build(BuildContext context) { into a different.dart file, and then just import it into Stateful widget in main.dart. My goal is to make my code neater and not have everything in the main.dart file. Thanks for your help!

import 'package:flutter/material.dart';


void main() {
  runApp(new TodoApp());
}

class TodoApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'To Do List',
      home: new TodoList()
    );
  }
}

class TodoList extends StatefulWidget {
  @override
  _TodoListState createState() => _TodoListState();
}

class _TodoListState extends State<TodoList> {
  List<String> _todoItems = [];
  
  void _addTodoItems() {
    setState(() { 
      int index = _todoItems.length;
      _todoItems.add('Item ' + index.toString());
    });
  }
  Widget _buildTodoList() {
    return new ListView.builder(
      itemBuilder: (context, index) {
      
        if (index < _todoItems.length) {
          return _buildTodoItem(_todoItems[index]);
        }
      },
    );
  }
  Widget _buildTodoItem(String todoText) {
    return new ListTile(
      title: new Text(todoText),
    );
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        centerTitle: true, 
        title: new Text(
          'To Do List',
          style: TextStyle(
            color: Colors.grey[200],
            fontSize: 25,
          ),

        ),
      ),

      body: _buildTodoList(),
      floatingActionButton: new FloatingActionButton(
        onPressed: _addTodoItems,
        tooltip: 'Add task',
        child: new Icon(Icons.add),
      ),

    );
  }
}

In Dart, all classes, methods and variables starting from _ are private (it's cannot be used outside current scope (if method is private - it's not available from call from the class, or if class is private - it's not available in other files)).

In your situation just create another file (like todo_list.dart ) and move TodoList and _TodoListState to it and import TodoList in main.dart .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM