颤振中模型之间的依赖关系

时间:2020-04-24 10:02:38

标签: sqlite flutter dart

请帮帮我。有一个包含多个表的数据库:

1)诗歌作者的名字。 2)诗歌的名字。

一个表使用ID链接到另一个表(在具有诗歌名称的表中,有一列具有作者ID)。

有必要通过单击打开该作者的作者诗歌。我不知道如何建立连接。

Authors.dart(作者模型)

Authors authorsFromJson(String str) {
  final jsonData = json.decode(str);
  return Authors.fromMap(jsonData);
}

String authorsToJson(Authors data) {
  final dyn = data.toMap();
  return json.encode(dyn);
}

class Authors {
  int id;
  String name;
  int count;

  Authors({
    this.id,
    this.name,
    this.count,
  });

  factory Authors.fromMap(Map<String, dynamic> json) => new Authors(
        id: json["c_id"],
        name: json["c_title"],
        count: json["c_i_count"],
      );

  Map<String, dynamic> toMap() => {
        "c_id": id,
        "c_title": name,
        "c_i_count": count,
      };
}

PoemsTitle.dart (PoemsTitle的模型)

PoemsTitle poemsTitleFromJson(String str) {
  final jsonData = json.decode(str);
  return PoemsTitle.fromMap(jsonData);
}

String poemsTitleToJson(PoemsTitle data) {
  final dyn = data.toMap();
  return json.encode(dyn);
}

class PoemsTitle {
  int id;
  String title;
  int authorsId;

  PoemsTitle({
    this.id,
    this.title,
    this.authorsId,
  });

  factory PoemsTitle.fromMap(Map<String, dynamic> json) => new PoemsTitle(
    id: json["ii_i_id"],
    title: json["ii_i_title"],
    authorsId: json["ii_col_int_2"],
  );

  Map<String, dynamic> toMap() => {
    "ii_i_id": id,
    "ii_i_title": title,
    "ii_col_int_2": authorsId,
  };
}

类别表中的 c_title 列必须与 items_info 表中的 ii_col_int_2 列关联。

DBProvider的方法:

...Future<List<Authors>> getAllAuthors() async {
    final db = await database;
    var res = await db.query('category');
    List<Authors> list = res.map((c) => Authors.fromMap(c)).toList();
    return list;
}

Future<List<PoemsTitle>> getAllPoemsTitle() async {
    final db = await database;
    var res = await db.query('items_info');
    List<PoemsTitle> list = res.map((c) => PoemsTitle.fromMap(c)).toList();
    return list;
}

以及FutureBuilder和ListView.builder中的页面:

这是一个小部件,单击相应的作者后即可在其中显示诗歌:

class FavoriteTab extends StatelessWidget {
  int authorId;
  int count;

  FavoriteTab({this.authorId, this.count});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: Padding(
        padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
        child: Container(
            padding: EdgeInsets.all(5),
            decoration: BoxDecoration(
                color: Theme.of(context).accentColor,
                borderRadius: BorderRadius.all(Radius.circular(30))
            ),
            child: FutureBuilder<List<PoemsTitle>>(
              future: DBProvider.db.getAllPoemsTitle(),
              builder: (context, snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  case ConnectionState.done:
                    {
                      if (snapshot.hasError) {
                        return Center(
                          child: Text(snapshot.error.toString()),
                        );
                      } else if (snapshot.hasData) {
                        return Scrollbar(
                            child: ListView.builder(
                              physics: BouncingScrollPhysics(),
                              itemCount: this.count,
                              itemBuilder: (context, index) {
                                PoemsTitle item = snapshot.data[index];
                                return ListTile(
                                  title: Text(item.title),
                                  leading: Icon(Icons.receipt),
                                  trailing: Icon(Icons.favorite, color: Colors.red, size: 34),
                                  onTap: () {

                                  },
                                );
                              },
                            )
                        );
                      }
                      return Center(
                          child: Text('No Data')
                      );
                    }
                  default:
                    return Container();
                }
              },
            )
        ),
      ),
    );
  }
}

这是作者的窗口小部件:

class MainTab extends StatefulWidget {
  @override
  _MainTabState createState() => _MainTabState();
}

class _MainTabState extends State<MainTab> {

  @override
  Widget build(BuildContext context) {
      return Padding(
        padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
        child: Container(
            padding: EdgeInsets.all(5),
            decoration: BoxDecoration(
                color: Theme.of(context).accentColor,
                borderRadius: BorderRadius.all(Radius.circular(30))
            ),
            child: FutureBuilder<List<Authors>>(
              future: DBProvider.db.getAllAuthors(),
              builder: (context, snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  case ConnectionState.done:
                    {
                      if (snapshot.hasError) {
                        return Center(
                          child: Text(snapshot.error.toString()),
                        );
                      } else if (snapshot.hasData) {
                        return Scrollbar(
                            child: ListView.builder(
                              physics: BouncingScrollPhysics(),
                              itemCount: snapshot.data.length,
                              itemBuilder: (context, index) {
                                Authors item = snapshot.data[index];
                                return ListTile(
                                  title: Text(item.name),
                                  leading: Icon(Icons.folder),
                                  trailing: Text(item.count.toString()),
                                  onTap: () {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => FavoriteTab(authorId: item.id, count: item.count)
                                      )
                                    );

                                  },
                                );
                              },
                            )
                        );
                      }
                      return Center(
                        child: Text('No Data')
                      );
                    }
                  default:
                    return Container();
                }
              },
            )
        ),
      );
    }
}

1 个答案:

答案 0 :(得分:0)

我认为问题出在FavoriteTab小部件中

future: DBProvider.db.getAllPoemsTitle(),

您总是在这里查询所有诗歌。正确的做法是在getPoemOfAuthor(int authorID)中创建类似DBProvider的方法,由于打开authorId时您通过了FavoriteTab,因此在FutureBuilder中必须致电:

future: DBProvider.db.getPoemOfAuthor(authorId),

希望这会有所帮助!