根据条件显示ListTile的数量

时间:2019-12-19 00:20:21

标签: flutter dart

我想开发一个有关五本书的应用程序,这些书都有不同的章节数,例如

  1. A书-20章
  2. B图书-14章
  3. C书-23章
  4. D书-18章
  5. E书-19章
  

我已经完成

     
    

the signIn page the signUp pagethe choose book page

  
     

我想做

     
    

the choose chapter page

  

注意:the choose book pagethe choose chapter page都使用清单

谈到选择章节页面时,我在显示根据书籍类型的ListTiles数量时遇到了问题,我应该为每本书创建不同的选择章节页面吗?(我害怕重复代码)或Flutter中的一项功能,可让您根据特定条件(如果可用)显示ListTiles的数量

我需要有关是否应该

的指南
  1. 为每本书创建不同的选择章节页面。
  2. 使用Flutter中的一项功能,可让您根据特定条件更新ListTiles。

the choose book page的{​​{1}}中

我尝试过的代码太

ListTile

2 个答案:

答案 0 :(得分:1)

class Chapters{
   String title;
   List<String> chapters;

   Chapters(this.title,this.chapters);
}

              // Inside your tap method
              onTap: ()
              {
                List<String> chaptersList= ["Chapter 1", "Chapter 2", "Chapter 3"];
                // you can pass arguments with named routes
                Navigator.pushNamed
                       (context, 
                       **Your_Next_Screen**,
                       arguments: Chapters(                               
                       'Book A',                              
                       chaptersList,       
                       ),                                                                                                                 
                );
              },

Your_Next_Screen 的构建方法中,检索数据,例如

@override
  Widget build(BuildContext context) {
    // Extract the arguments from the current ModalRoute settings and cast
    // them as Chapters.
    final Chapters args = ModalRoute.of(context).settings.arguments;

    var title= args.title;
    var list= args.chapters;

    return Scaffold(
      // your widget
    );
  }
}

答案 1 :(得分:0)

您可以为此使用ListView.builder()Docs)。它带有一些参数,例如要构建的项目数,以及要构建的N个元素中的每个元素都将调用的构建器方法。

ListView.builder(
  itemCount: book.chapters.length, // Use the number of chapters here
  itemBuilder: (BuildContext context, int index) {
    // Each chapter will be a ListTile, you can add more parameters, or use whatever widget
    return ListTile(title: Text("Chapter $index"));
  }
)

Here's an example,由Flutter团队提供。