如何在Flutter中创建动态ListView?

时间:2019-07-07 15:41:03

标签: flutter dart

我尝试使用传递到ListView.Builder中的TileList,但收到错误:错误:无法将参数类型'(BuildContext,int,Items)→卡'分配给参数类型'(BuildContext,int)→小部件”。 (argument_type_not_assignable)。

我将_makeCard和_makeTyle定义为没有成功的小部件。

import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:app_settings/app_settings.dart';
import 'package:coffee/models/settings_items.dart';

class Selections extends StatefulWidget {

  @override
  State<Selections> createState() => _Selections();
  final List<String> menu;
  Selections(this.menu);

}

class _Selections extends State<Selections> {

  List items;

  @override
  void initState() {
    items = getItems();
    super.initState();
  }

 Card _makeCard(BuildContext context, int index, Items item) {
    return Card(
      elevation: 8.0,
      margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
      child: Container(
        decoration: BoxDecoration(color: Color.fromRGBO(64, 75, 96, .0)),
        child: _buildMenu(context, index, item),
      ),
    );
  }


  ListTile _buildMenu(BuildContext context, int index, Items item) {
  return ListTile(
      contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
      leading: Container(
        padding: EdgeInsets.only(right: 12.0),
        decoration: new BoxDecoration(
          border: new Border(
            right: new BorderSide(width: 1.0, color: Colors.blue),
          ),
        ),
        child: Icon(
          Icons.location_on,
          color: Colors.redAccent,
        ),
      ),
      title: Text(
        item.title,
        style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
      ),
      onTap: () {
        AppSettings.openLocationSettings();
      },
    );
}

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ListView.builder(
          itemBuilder: _makeCard,
          itemCount: 2,
          scrollDirection: Axis.vertical,
          shrinkWrap: true),
    );
  }

  List getItems() {
    return [
      Items(
          title: "Turn on Location Services!"
      ),
      Items(
          title: "My Profile"
      ),
    ];
  }


}

将显示两个ListTIles:一个带有文本“ Turn on Location Services”,另一个带有“我的个人资料”。

1 个答案:

答案 0 :(得分:1)

删除_makeCard中的items参数,然后在函数中检索它:

Card _makeCard(BuildContext context, int index) {
  Items item = items[index];
  return Card(
    elevation: 8.0,
    margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
    child: Container(
      decoration: BoxDecoration(color: Color.fromRGBO(64, 75, 96, .0)),
      child: _buildMenu(context, index, item),
    ),
  );
}

OR

build()中,对builder参数使用higher order function,以使函数参数匹配:

return Container(
  child: ListView.builder(
    itemBuilder: (context, index) => _makeCard(context, index, items[index]),
    itemCount: 2,
    scrollDirection: Axis.vertical,
    shrinkWrap: true),
);