Flutter Tutorials

Flutter app development tutorials


flutter – ListView add item

main.dart


import 'package:flutter/material.dart';

void main() => runApp(const FlutterExample());

class FlutterExample extends StatelessWidget {
  const FlutterExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Example',
        theme: ThemeData(primarySwatch: Colors.amber),
        home: const StateExample()
    );
  }
}

class StateExample extends StatefulWidget {
  const StateExample({Key? key}) : super(key: key);

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

class _StateExampleState extends State<StateExample>{
  final numbers = List<int>.generate(4, (i) => i + 1);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFEFEFA),
      appBar: AppBar(
          title: const Text("Flutter - ListView Add Item")
      ),
      body: bodyContent(),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        backgroundColor: Colors.blueAccent,
        foregroundColor: Colors.white70,
        onPressed: (){
          setState(() {
            numbers.insert(
                numbers.length,
                numbers.length + 1
            );
          });
        },
      ),
    );
  }

  bodyContent() {
    return ListView.builder(
        itemCount: numbers.length,
        itemBuilder: (context, index) {
          return Card(
            color: const Color(0xFFE6E6FA),
            child: ListTile(
              contentPadding: const EdgeInsets.all(10),
              title: Text("${numbers[index]}"),
            ),
          );
        }
    );
  }
}

More flutter tutorials



About Me

Flutter Developer

Design a site like this with WordPress.com
Get started