1. 程式人生 > 其它 >flutter ListView橫向列表&不定長列表

flutter ListView橫向列表&不定長列表

ListView橫向列表

效果:

(可以左右滑動)

程式碼形式1:

main.dart

import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'dasldjalsdjasldj',
      home: Scaffold(
        appBar: new AppBar(title: new Text('new texrdasdasd'),),
        body: Center(
          child: Container(
            height: 
200.0, child: new ListView( scrollDirection: Axis.horizontal, children: [ new Container( width: 120, color: Colors.lime, ), new Container( width: 120, color: Colors.pinkAccent, ),
new Container( width: 120, color: Colors.purpleAccent, ), new Container( width: 120, color: Colors.deepPurple, ), ], ), ), ) ), ); } }
void main() { runApp(MyApp()); }

程式碼形式2:

main.dart

import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'dasldjalsdjasldj',
      home: Scaffold(
        appBar: new AppBar(title: new Text('new texrdasdasd'),),
        body: Center(
          child: Container(
            height: 200.0,
            child: Mylist(),
          ),
        )
      ),
    );
  }
}


class Mylist extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      scrollDirection: Axis.horizontal,
      children: [
        new Container(
          width: 120,
          color: Colors.lime,
        ),
        new Container(
          width: 120,
          color: Colors.pinkAccent,
        ),
        new Container(
          width: 120,
          color: Colors.purpleAccent,
        ),
        new Container(
          width: 120,
          color: Colors.deepPurple,
        ),
      ],
    );
  }
}
void main() {
  runApp(MyApp());
}

ListView不定長列表

效果:

程式碼:

main.dart

import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {

  final List<String> items;
  MyApp({required this.items});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'dasldjalsdjasldj',
      home: Scaffold(
        appBar: new AppBar(title: new Text('new texrdasdasd'),),
        body: new ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
          return new ListTile(
            title: new Text('${items[index]}'),
          );
        })
      ),
    );
  }
}
void main() {
  runApp(MyApp(items: new List<String>.generate(20, (index) => "物品 $index"),));
}