2021年7月24日 星期六

[又重學flutter]控制context與navigator

 

//main.dart
import 'package:flutter/material.dart';
import 'page2.dart';

List<String> pageList = ['/page2'];
void main() {

  runApp(MaterialApp(
    initialRoute: '/', routes: {
    '/': (BuildContext context) => HomePage(),
    '/page2': (BuildContext context) => Page2()
  }));
}

class HomePage extends StatefulWidget {
  
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home')),
      body: Column(
        children: List.generate(pageList.length, (index) {
          Map<String, String> arguments = {'title': 'Page2'};
          return GestureDetector(
              onTap: () {
                Navigator.of(context).pushNamed('/page2', arguments: arguments);
              },
              child: _textGenerator(pageList[index]));
        }),
      ),
    );
  }
}

Widget _textGenerator(String text) {
  return Padding(padding: EdgeInsets.all(10.0), child: Text(text));
}

//page2.dart
import 'package:flutter/material.dart';

class Page2 extends StatelessWidget {
  Page2();
  
  Widget build(BuildContext context) {
    final routes = ModalRoute.of(context);
    if (routes == null) return SizedBox.shrink();
    Map arguments = routes.settings.arguments as Map;
    return Scaffold(
      appBar: AppBar(
        title: Text('${arguments['title']}'),
      ),
    );
  }
}




按下/page2後
































沒有留言:

張貼留言