更新数据库时,FutureBuilder不会更新

时间:2020-10-23 22:33:29

标签: flutter sqflite flutter-futurebuilder

我当时正在一个简单的笔记应用程序中工作,这是我的代码。

我只是通过这个示例来预览问题

这是导航到创建页面的主页,并使用futureBuilder显示数据库中的数据

import 'package:flutter/material.dart';
import 'package:futurebuilder_test/db.dart';
import 'create.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final DatabaseHelper db = DatabaseHelper.instance;
  Future futureData;

  @override
  void initState() {
    futureData = _getData();
    super.initState();
  }

  Future _getData() async{
    return await db.queryAllRows('notes');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => _navigateToCreatePage(context),
      ),

      body: FutureBuilder(
        future: _getData(),
        builder: (BuildContext context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, index) {
                return ListTile(
                  title: Text(snapshot.data[index]['title']),
                );
              },
            );
          }
          
          return Text('Empty');
        },
      ),
    );
  }
}

void _navigateToCreatePage(context) {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => CreatePage())
  );
}

这是创建页面

import 'package:flutter/material.dart';
import 'package:futurebuilder_test/db.dart';

class CreatePage extends StatelessWidget {
  final DatabaseHelper db = DatabaseHelper.instance;

  final TextEditingController title = TextEditingController();
  final TextEditingController description = TextEditingController();

  void save(context) async {
    await db.insert(
      'notes', {'title': title.text, 'description': description.text}
    );
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,

          children: [
            TextField(
              decoration: InputDecoration(hintText: 'Title'),
              controller: title,
            ),

            TextField(
              decoration: InputDecoration(hintText: 'Title'),
              controller: description,
            ),

            RaisedButton(
              child: Text('Save'),
              onPressed: () => save(context),
            )
          ],
        ),
      ),
    );
  }
}

当用户单击“保存”按钮时,它将向数据库添加新注释,然后将页面弹出回到主屏幕。假定,将来的构建器在向数据库提交新数据后会更新其数据。 但这没有发生。有人可以帮我吗。

1 个答案:

答案 0 :(得分:0)

您应该使用this处理上一页,或者使用state management处理所有内容。