0

How to create a listview through ListView.Custom. I tried with ListView.Builder and ListView.Separted.Both are working fine.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text(widget.title),
        ),
        body: ListView.custom(
          scrollDirection: Axis.vertical,
          reverse: false,
          childrenDelegate: new MyCustomDelegate(),));
  }
}

List<String> listItems = ["One", "Two", "Three", "Four","Five","Six"];


class MyCustomDelegate extends SliverChildDelegate {

 @override
   int get estimatedChildCount => listItems.length;  

  @override
    bool shouldRebuild(SliverChildDelegate oldDelegate) {
      return true;
    }
  @override
    Widget build(BuildContext context, int index) {
      return Container(padding: new EdgeInsets.only(top: 16.0),
      child: new Text(listItems[index]),);

    }
}

Can anyone please help me out for this. Thanks in advance.

1 Answer 1

1

You should add a validation to ensure your item is in the range:

     @override
    Widget build(BuildContext context, int index) {
      return index < estimatedChildCount
          ? Container(
              padding: new EdgeInsets.only(top: 16.0),
              child: new Text(listItems[index]),
            )
          : null;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.