颤振,显示数据库信息问题

时间:2020-04-20 13:07:23

标签: database flutter dart sqflite

所以我试图创建一个简单的便笺应用程序,以使用SQFlite将便笺保存在数据库中,我添加了一个“添加便笺”按钮,其中有两个用于标题和文本的TextField,并且可以正常工作,其想法是显示标题和正文中卡片的标题,我的问题是,仅在我重新启动应用程序后才创建并显示带有两个文本的卡片,而不是按“保存”后才显示。 到目前为止,这是代码:

main.dart:

import 'package:flutter/material.dart';

import 'home_screen.dart';
import 'note_inherited_widget.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return NoteInheritedWidget(
          MaterialApp(
        home: HomeScreen(),
        theme: ThemeData(
            primaryColor: Colors.deepOrange, accentColor: Colors.deepPurple),
      ),
    );
  }
}

home_screen.dart

import 'package:flutter/material.dart';

import 'package:simple_notes/note_inherited_widget.dart';
import 'package:simple_notes/providers/note_providers.dart';
import './note_inherited_widget.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final TextEditingController titleController = TextEditingController();
  final TextEditingController textController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    titleController.dispose();
    textController.dispose();
    super.dispose();
  }

  DummyDataProvider notes;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    notes = NoteInheritedWidget.of(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Simple Notes'),
          centerTitle: true,
        ),
        body: FutureBuilder(
            future: NoteProvider.getNoteList(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                final notes = snapshot.data;
                return ListView.builder(
                  itemBuilder: (context, index) {
                    return Card(
                      child: Column(
                        children: <Widget>[
                          NoteTitle(notes[index]['title']),
                          NoteText(notes[index]['text'])
                        ],
                      ),
                    );
                  },
                  itemCount: notes.length,
                );
              }
              return Center(child: CircularProgressIndicator());
            }
            ),
        bottomNavigationBar: (FlatButton(
            onPressed: () {
              showMyDialog(context);
            },
            child: Text('Add note'))));
  }

  Future<void> showMyDialog(
    BuildContext context,
  ) {
    return showDialog<void>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Column(
              children: <Widget>[
                TextField(
                  controller: titleController,
                ),
                TextField(
                  controller: textController,
                )
              ],
            ),
            actions: <Widget>[
              MaterialButton(onPressed: () {
                final title = titleController.text;
                final text = textController.text;
                NoteProvider.insertNote({
                  'title': title,
                  'text': text
                });
                Navigator.pop(context);
              }, 
              child: Text('save')
              )
            ],
          );
        });
  }
}

class NoteTitle extends StatelessWidget {
  final String title;

  NoteTitle(this.title);

  @override
  Widget build(BuildContext context) {
    return Text(
      title,
      style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
    );
  }
}

class NoteText extends StatelessWidget {
  final String text;

  NoteText(this.text);

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: TextStyle(
        color: Colors.grey.shade600,
      ),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
  }
}

class SaveButton extends StatelessWidget {
  final Function onPressed;

  SaveButton(this.onPressed);

  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      onPressed: () {

        Navigator.pop(context);
      },
      child: Text('Save'),
    );
  }
}

notes_provider.dart

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class NoteProvider {
  static Database db;

  static Future open() async {
    db = await openDatabase(join(await getDatabasesPath(), 'notes.db'),
    version: 1,
    onCreate: (Database db, int version) async {
      db.execute('''
      CREATE TABLE notes(
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        text TEXT NOT NULL
      );
      ''');
     }
    );
  }

  static Future<List<Map<String, dynamic>>> getNoteList() async {
      if (db == null) {
        await open();
      }
      return await db.query('Notes');
    }

    static Future insertNote (Map<String, dynamic> note) async {
      await db.insert('Notes', note);
    }
}

由于我正在学习颤振编程,所以我一直无法解决这个问题。如果你们能为我指出解决这个问题的正确方向,那就太好了。

谢谢!

0 个答案:

没有答案