为什么ListView没有显示用户输入的文本?

3

我需要你的帮助。

我正在为我的应用程序编写一个功能,用户通过按下“添加”按钮添加内容,然后导航到添加页面,然后从添加页面在列表视图中添加一个新的ListTile。但是我不知道为什么用户输入的文本无法显示。有人可以帮我吗?

import 'package:flutter/material.dart';
import 'storage for each listview.dart';
import 'package:provider/provider.dart';
import 'adding page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => Storage(),
      child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage()
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<Storage>(context, listen: false);
    final storageaccess = provider.storage;
    return Scaffold(
        appBar: AppBar(
          title: Text('app'),
        ),
        body: ListView.builder(
            itemCount: storageaccess.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(storageaccess[index].title),
                subtitle: Text(storageaccess[index].titlediary.toString()),
                onTap: () {},
                onLongPress: () {
                  //delete function here
                },
              );
            }),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => addpage()));
          }, //void add
          tooltip: 'add diary',
          child: Icon(Icons.add),
        ) // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}



/// this one I did not do anything first this one for later today just make UI
class Things {
  String title;
  DateTime titlediary;

  Things({required this.title, required this.titlediary});
}

class addpage extends StatefulWidget {
  @override
  _addpageState createState() => _addpageState();
}

class _addpageState extends State<addpage> {

  String title = '';

  @override
  Widget build(BuildContext context) {
    final TextEditingController titleController=TextEditingController(text: title);
    final formKey = GlobalKey<FormState>();
    return Scaffold(
      appBar: AppBar(
        title: Text('enter page ',style: TextStyle(fontSize: 30),),
      ),
      body:Form(
        key: formKey,
        child: Column(
          children: [
            TextFormField(
              controller: titleController,
              autofocus: true,
              validator: (title) {
                if (title!.length < 0) {
                  return 'enter a title ';
                } else {
                  return null;
                }
              },
              decoration: InputDecoration(
                border: UnderlineInputBorder(),
                labelText: 'title',
              ),
            ),
            SizedBox(height: 8),
            ElevatedButton(
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.black),
              ),
              onPressed: () {
                if (formKey.currentState!.validate()) {
                  final accessthing = Things(
                    title: title,
                    titlediary: DateTime.now(),
                  );
                  final provideraccess = Provider.of<Storage>(context, listen: false);
                  provideraccess.add(accessthing);
                  Navigator.of(context).push(
                      MaterialPageRoute(
                          builder: (context) =>MyHomePage()));
                }
              },
              child: Text('Save'),
            ),
          ],
        ),),);
  }
}

class Storage extends ChangeNotifier {
  List<Things> storage = [
    Things(
      title: 'hard code one ',
      titlediary: DateTime.now(),
    ),
    Things(
      title: 'hard code two ',
      titlediary: DateTime.now(),
    ),
    Things(
      title: 'hard code two ',
      titlediary: DateTime.now(),
    ),
    Things(
      title: 'hard code two ',
      titlediary: DateTime.now(),
    ),
  ];
  void add(Things variablethings) {
    storage.add(variablethings);
  } notifyListeners();
}

用户点击添加按钮后,将转到添加页面,然后在点击保存后,数据将保存到存储页面,然后提供者将添加用户提供的数据,但文本不会显示在列表瓷砖上。

1个回答

2
我猜测这是因为您再次使用导航到主页,所以出现了这种情况。
Navigator.of(context).push(
                      MaterialPageRoute(
                          builder: (context) =>MyHomePage()));

但是这一次它没有连接到您的提供程序上下文。

[ 详细说明:由于您在MyApp中使用了ChangeNotifierProvider(),然后将MyHomePage()连接在那里。但是,如果您再次在Navigator中推出,那么fluter会创建一个MyHomePage() widget的单独实例。这将不会连接到MyApp中的ChangeNotifierProvider()。 ]。

取而代之的是,使用Navigator.of(context).pop(); 并且在onPressed()中使用以下内容:

floatingActionButton: FloatingActionButton(
 --->     onPressed: () async {
 --->       await Navigator.push(
                context, MaterialPageRoute(builder: (context) => addpage()));
 --->       setState((){});
          },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接