ListView
is a scrollable widget and Column
is not scrollable. When you want to add a sing list view you get errors.
Things get more complication when you want to add two list views inside the column widget.
ListView inside Column Example
Let’s create a new Flutter Project and add the ListView
inside the Column
widget.
Problem:
import 'package:flutter/material.dart';
class ListViewInsideColumn extends StatelessWidget {
const ListViewInsideColumn({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('CodewithHussain'),
),
body: Column(
children: [
ListView(
children: const [
Text('List 1'),
Text('List 1'),
Text('List 1'),
],
),
ListView(
children: const [
Text('List 2'),
Text('List 2'),
Text('List 2'),
],
),
],
),
);
}
}
Now, when you restart or hot reload the app. You get error messages:
Vertical viewport was given unbounded height.
Solution: Use Expanded Widgets
Flutter Expanded
widget is an excellent option for most use cases.
Just Wrap both ListView
widgets inside Expanded
.
Expanded(
child: ListView(
children: const [
Text('List 1'),
Text('List 1'),
Text('List 1'),
],
),
),
Expanded(
child: ListView(
children: const [
Text('List 2'),
Text('List 2'),
Text('List 2'),
],
),
),
Your problem is Solved.
Complete Code:
import 'package:flutter/material.dart';
class ListViewInsideColumn extends StatelessWidget {
const ListViewInsideColumn({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('CodewithHussain'),
),
body: Column(
children: [
Expanded(
child: ListView(
children: const [
Text('List 1'),
Text('List 1'),
Text('List 1'),
],
),
),
Expanded(
child: ListView(
children: const [
Text('List 2'),
Text('List 2'),
Text('List 2'),
],
),
),
],
),
);
}
}
Conclusion:
Adding ListView inside Column is sometimes a difficult task because we don’t use the expanded widget. Here we solve the problem by using Expanded
the widget in our Flutter app.
Read more:
- Flutter shows toast messages
- Flutter form validation
- Flutter gradient backgrounds
- Flutter Lock Device Orientation
Hope you like this flutter tutorial. Thanks