Подтвердить что ты не робот

Flutter: могу ли я добавить строку заголовка в ListView

Очень плохо знакомы с Флаттер. Я был в состоянии использовать HTTP-запросы для данных, построить ListView, редактировать строку в этом списке и другие основы. Отличная среда.

Мне удалось собрать плохо сконструированный заголовок для ListView... но я знаю, что это неправильно. Я не могу правильно выстроить текст заголовка.

Я вижу, что класс Drawer имеет класс DrawerHeader, но не вижу, что ListView имеет ListViewHeader.

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('Contacts'),
          actions: [
            new IconButton(icon: new Icon(Icons.add_circle),
                onPressed: getCustData
            ),
          ],
        ),
        //body:
        body: new Column(
            children: [
              new Row(
                  children: [
                    new Expanded(child: new Text('', style: new TextStyle(height: 3.0, fontSize: 15.2, fontWeight: FontWeight.bold,))),
                    new Expanded(child: new Text('First Name', style: new TextStyle(height: 3.0, fontSize: 15.2, fontWeight: FontWeight.bold,))),
                    new Expanded(child: new Text('Last Name', style: new TextStyle(height: 3.0, fontSize: 15.2, fontWeight: FontWeight.bold,))),
                    new Expanded(child: new Text('City', style: new TextStyle(height: 3.0, fontSize: 15.2, fontWeight: FontWeight.bold,))),
                    new Expanded(child: new Text('Customer Id', style: new TextStyle(height: 3.0, fontSize: 15.2, fontWeight: FontWeight.bold,))),
                    new Expanded(child: new Text('', style: new TextStyle(height: 3.0, fontSize: 15.2, fontWeight: FontWeight.bold,))),
                  ]
              ),

new Expanded(child:Container( child: ListView.builder( itemCount: data == null ? 0 : data.length, itemBuilder: (BuildContext context, int index) { return new InkWell( onTap: () { Navigator.push( context, new MaterialPageRoute( builder: (context) => new APIDetailView(data[index])), ); }, child: new ListTile( //return new ListTile( onTap: null, leading: new CircleAvatar( backgroundColor: Colors.blue, child: new Text(data[index]["FirstName"][0]), ), title: new Row( children: <Widget>[ new Expanded(child: new Text(data[index]["FirstName"])), new Expanded(child: new Text(data[index]["LastName"])), new Expanded(child: new Text(data[index]["Bill_City"])), new Expanded(child: new Text(data[index]["Customer_Id"])), ] ) ), ); }, //itemBuilder ), ), ), ] ) );

} }

Благодаря.

enter image description here

4b9b3361

Ответ 1

Вот как я это решил. Спасибо Наджера, что заставил меня задуматься о других решениях.

В первом столбце тела я использовал тот же макет для своего заголовка, что и для ListTile.

Поскольку мой ListTile данных, в данном случае, включает CircleAvatar, все горизонтальные интервалы немного смещены... 5 столбцов, в которых отображается CircleAvatar... затем 4 столбца с равным интервалом.

Итак... я добавил ListTile к первому столбцу тела, CircleAvatar с backgroundColor из прозрачного, а затем строку из моих 4 заголовков.

        new ListTile(
        onTap: null,
        leading: new CircleAvatar(
          backgroundColor: Colors.transparent,
        ),
        title: Row(
            children: <Widget>[
              new Expanded(child: new Text("First Name")),
              new Expanded(child: new Text("Last Name")),
              new Expanded(child: new Text("City")),
              new Expanded(child: new Text("Id")),
            ]
        ),
      ),

enter image description here

Ответ 2

Верните заголовок как первую строку itemBuilder:

ListView.builder(
    itemCount: data == null ? 1 : data.length + 1,
    itemBuilder: (BuildContext context, int index) {
        if (index == 0) {
            // return the header
            return new Column(...);
        }
        index -= 1;

        // return row
        var row = data[index];
        return new InkWell(... with row ...);
    },
);

Ответ 3

Вы можете добавить столбец к первому элементу в списке элементов следующим образом:

new ListView.builder
  (
    itemCount: litems.length,
    itemBuilder: (BuildContext ctxt, int index) {
     if(index==0)
{
return
Column(
children: <Widget>[
Header();
rowContent(index);
]
else{
return rowContent(index);
}
    }
  )

Ответ 4

1. you can add container and lisview in Column ,

import 'package:flutter/material.dart';

void main() => runApp(MyApp());


class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState расширяет состояние {

@override
void initState() {



  // TODO: implement initState
  super.initState();
 }

 @override
 Widget build(BuildContext context) {
  return MaterialApp(
  debugShowCheckedModeBanner: false,
   home: Scaffold(
    appBar: AppBar(
      title: Text("Demo App1"),
    ),
    body: Column(
      children: <Widget>[
        Container(
          height: 40.0,
          child: Row(
            children: <Widget>[
              Container(
                padding: EdgeInsets.all(4.0),
              width: 100.0
              ,child: Text("Name",style: TextStyle(fontSize: 18),)),
              Container(
                  padding: EdgeInsets.all(4.0),
                  width: 100.0
                  ,child: Text("Age",style: TextStyle(fontSize: 18),)),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
          itemCount: 100
          ,itemBuilder: (BuildContext context,int index){
            return Row(
              children: <Widget>[
                Container(
                    padding: EdgeInsets.all(4.0),
                    width: 100.0
                    ,child: Text("Name $index",
                style:TextStyle(fontSize:18),)),
                Container(
                    padding: EdgeInsets.all(4.0),
                    width: 100.0
                    ,child: Text("Age $index",
                style: TextStyle(fontSize: 18),))
              ],
            );
          }),
        )
        ],
       ),
       ),
      );
     }
    }