Flutter 案例学习之:ListView
2018-09-09 本文已影响8人
与蟒唯舞
GitHub:https://github.com/happy-python/flutter_demos/tree/master/listview_demo
ListView 目录结构lib/main.dart
import 'package:flutter/material.dart';
import 'package:listview_demo/pages/homepage.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Flutter Tutorial",
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
lib/model/city.dart
class City {
final String name;
final String image;
final String population;
final String country;
City({this.name, this.image, this.population, this.country});
static List<City> allCities() {
var cities = new List<City>();
cities.add(new City(
name: "Delhi",
country: "India",
population: "19 mill",
image: "delhi.png",
));
cities.add(new City(
name: "London",
country: "Britain",
population: "8 mill",
image: "london.png",
));
cities.add(new City(
name: "Vancouver",
country: "Canada",
population: "2.4 mill",
image: "vancouver.png",
));
cities.add(new City(
name: "New York",
country: "USA",
population: "8.1 mill",
image: "newyork.png",
));
cities.add(new City(
name: "Paris",
country: "France",
population: "2.2 mill",
image: "paris.png",
));
cities.add(new City(
name: "Berlin",
country: "Germany",
population: "3.7 mill",
image: "berlin.png",
));
return cities;
}
}
lib/pages/homepage.dart
import 'package:flutter/material.dart';
import 'package:listview_demo/model/city.dart';
class HomePage extends StatelessWidget {
final List<City> _allCities = City.allCities();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cites around world"),
),
body: Padding(
padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return _getItemUI(context, index);
},
itemCount: _allCities.length,
),
),
);
}
Widget _getItemUI(BuildContext context, int index) {
return Card(
child: Column(
children: <Widget>[
ListTile(
leading: Image.asset(
"assets/" + _allCities[index].image,
fit: BoxFit.cover,
width: 100.0,
),
title: Text(
_allCities[index].name,
style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.bold),
),
subtitle: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
_allCities[index].country,
style: TextStyle(
fontSize: 13.0,
),
),
Text(
"Population: ${_allCities[index].population}",
style: TextStyle(
fontSize: 11.0,
),
),
],
),
onTap: () {
_showSnackBar(context, _allCities[index]);
},
)
],
),
);
}
_showSnackBar(BuildContext context, City item) {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text("${item.name} is a city in ${item.country}"),
backgroundColor: Colors.amber,
),
);
}
}
由于所有这些图像都静态地包含在项目中,为了显示图像,我们需要在pubspec.yaml
(主配置文件)中进行很少的配置,如下所示:
assets:
- assets/berlin.png
- assets/delhi.png
- assets/london.png
- assets/newyork.png
- assets/paris.png
- assets/vancouver.png