使用 RouteSettings 将 'double' 参数传递给其他页面中的小部件的问题

Issue for pass 'double' arguments to widget in others pages with RouteSettings

我的应用程序有问题...

我只想在用户使用 ElevatedButton 时将两个 'double' 参数传递给其他页面中的小部件,并恢复地图中设置坐标的参数。

我通过阅读 Flutter.dev 上的文档尝试了所有方法来做到这一点,但我得到的任何值都不是 Null...

Main.dart :

import 'package:flutter/material.dart';
import 'package:booki3/route/route.dart' as route;

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Booking',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      onGenerateRoute: route.controller,
      initialRoute: route.home,
    );
  }
}

Home.dart :

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:booki3/views/maps.dart';
import 'package:booki3/route/route.dart' as route;

const dgreen = Color(0xFF54D3C2);

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const MyAppBar(),
        body: SingleChildScrollView(
          child: Column(
            children: [
              const SearchSection(),
              HotelSection(),
            ],
          ),
        ));
  }
}

class Data {
  double coordx = 45.20;
  double coordy = 20.50;
}

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(50);
  @override
  Widget build(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back,
          color: Colors.grey[800],
          size: 20,
        ),
        onPressed: null,
      ),
      title: Text(
        'Explore',
        style: GoogleFonts.nunito(
          color: Colors.black,
          fontSize: 22,
          fontWeight: FontWeight.w800,
        ),
      ),
      centerTitle: true,
      actions: [
        IconButton(
          icon: Icon(
            Icons.favorite_outline_rounded,
            color: Colors.grey[800],
            size: 20,
          ),
          onPressed: null,
        ),
        IconButton(
          icon: Icon(
            Icons.place,
            color: Colors.grey[800],
            size: 20,
          ),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const MyMaps(data: Data),
              ),
            );
          },
        ),
      ],
      backgroundColor: Colors.white,
    );
  }
}

Maps.dart :

第 25 行,我输入了随机值,否则页面将无法打开...最后,我想输入 Data 的值。但到目前为止我无法让他们回来。

import 'package:booki3/views/home.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MyMaps extends StatefulWidget {
  const MyMaps({Key? key, required data}) : super(key: key);

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

class _MyAppState extends State<MyMaps> {
  late GoogleMapController mapController;

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    final data = ModalRoute.of(context)!.settings.arguments as Data;

    debugPrint(data.toString());

    LatLng _center = const LatLng(25.32, 2.5); // <= Two 'double' of Data..

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Maps Sample App'),
          backgroundColor: Colors.green[700],
        ),
        body: GoogleMap(
          onMapCreated: _onMapCreated,
          initialCameraPosition: CameraPosition(
            target: _center,
            zoom: 11.0,
          ),
        ),
      ),
    );
  }
}

Route.dart :

import 'package:flutter/material.dart';
import 'package:booki3/views/home.dart';
import 'package:booki3/views/maps.dart';

const String home = "home";
const String maps = "maps";

Route<dynamic> controller(RouteSettings settings) {
  switch (settings.name) {
    case home:
      return MaterialPageRoute(builder: (context) => const HomePage());
    case maps:
      return MaterialPageRoute(
        builder: (context) => const MyMaps(
          data: Data,
        ),
        settings: const RouteSettings(
          arguments: Data,
        ),
      );
    default:
      throw ('This route name not exist');
  }
}

对于解决方案的大牛,我收到以下错误消息: Error Message

新 Home.dart :

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:booki3/views/maps.dart';
import 'package:booki3/route/route.dart' as route;

const dgreen = Color(0xFF54D3C2);

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const MyAppBar(),
        body: SingleChildScrollView(
          child: Column(
            children: [
              const SearchSection(),
              HotelSection(),
            ],
          ),
        ));
  }
}

class Data {
  double coordx = 45.20;
  double coordy = 20.50;

  @override
  String toString() => 'Data(coordx: $coordx, coordy: $coordy)'; // just to prin
}

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(50);
  @override
  Widget build(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back,
          color: Colors.grey[800],
          size: 20,
        ),
        onPressed: null,
      ),
      title: Text(
        'Explore',
        style: GoogleFonts.nunito(
          color: Colors.black,
          fontSize: 22,
          fontWeight: FontWeight.w800,
        ),
      ),
      centerTitle: true,
      actions: [
        IconButton(
          icon: Icon(
            Icons.favorite_outline_rounded,
            color: Colors.grey[800],
            size: 20,
          ),
          onPressed: null,
        ),
        IconButton(
          icon: Icon(
            Icons.place,
            color: Colors.grey[800],
            size: 20,
          ),
          onPressed: () {
            Navigator.of(context).pushNamed(
              route.maps,
              arguments: Data,
            );
          },
        ),
      ],
      backgroundColor: Colors.white,
    );
  }
}

新 Route.dart :

import 'package:flutter/material.dart';
import 'package:booki3/views/home.dart';
import 'package:booki3/views/maps.dart';

const String home = "home";
const String maps = "maps";

Route<dynamic> controller(RouteSettings settings) {
  final args = settings.arguments; // get the arguments here

  switch (settings.name) {
    case home:
      return MaterialPageRoute(builder: (context) => const HomePage());
    case maps:
      return MaterialPageRoute(
        builder: (context) => MyMaps(
          data: args as Data,
        ),
      );
    default:
      throw ('This route name not exist');
  }
}

新 Maps.dart :

import 'package:booki3/views/home.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MyMaps extends StatefulWidget {
  const MyMaps({
    Key? key,
    required this.data,
  }) : super(key: key);

  final Data data;

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

class _MyAppState extends State<MyMaps> {
  late GoogleMapController mapController;

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    final data = widget.data;

    debugPrint(data.toString());

    LatLng _center = LatLng(data.coordx, data.coordy);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Maps Sample App'),
          backgroundColor: Colors.green[700],
        ),
        body: GoogleMap(
          onMapCreated: _onMapCreated,
          initialCameraPosition: CameraPosition(
            target: _center,
            zoom: 11.0,
          ),
        ),
      ),
    );
  }
}

提前感谢您的帮助,因为我不知道该怎么办了..我觉得我已经尝试了一切..

爱你;)

好吧,让我们一步一步来,在Data class中我只放了toString这样当你打印它显示值(没有显示)。

当您想将所有 class 发送到页面 Maps 时,问题就来了,这是不可能的(在这种情况下),您必须发送的是class 的一个实例,因此我们创建它。

另一方面,你将使用 pushNamed 因为你自己告诉它它们在路线中被称为“家”或“地图”,所以我们要使用它们,而不是创建另一个 MaterialPageRoute 如果它们已经在你的路线中,你明白了吗?

首页:

class Data {
  double coordx = 45.20;
  double coordy = 20.50;

  @override
  String toString() => 'Data(coordx: $coordx, coordy: $coordy)'; // just to print
}

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(50);
  @override
  Widget build(BuildContext context) {
    final newData = Data(); // new instance creation

    return AppBar(
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back,
          color: Colors.grey[800],
          size: 20,
        ),
        onPressed: null,
      ),
      title: const Text(
        'Explore',
        style: TextStyle(
          color: Colors.black,
          fontSize: 22,
          fontWeight: FontWeight.w800,
        ),
      ),
      centerTitle: true,
      actions: [
        IconButton(
          icon: Icon(
            Icons.favorite_outline_rounded,
            color: Colors.grey[800],
            size: 20,
          ),
          onPressed: null,
        ),
        IconButton(
          icon: Icon(
            Icons.place,
            color: Colors.grey[800],
            size: 20,
          ),
          onPressed: () {
            Navigator.of(context).pushNamed( // using pushNamed not push
              "maps",
              arguments: newData, // send the instance
            );
          },
        ),
      ],
      backgroundColor: Colors.white,
    );
  }
}

路线 :

Route<dynamic> controller(RouteSettings settings) {
  final args = settings.arguments; // get the arguments here 

  switch (settings.name) {
    case home:
      return MaterialPageRoute(builder: (context) => const HomePage());

    case maps:
      return MaterialPageRoute(
        builder: (context) => MyMaps( // we delete the settings and pass directly in the MyMaps
          data: args as Data,
        ),
      );
    default:
      throw ('This route name not exist');
  }
}

最后,一旦创建实例,然后通过参数发送到路由并最终到达这里,为了获得该实例,我们只需在其构造函数中添加最终变量即可。

剩下唯一要做的就是将其放入 LatLng 中! :D

地图:

class MyMaps extends StatefulWidget {
  const MyMaps({
    Key? key,
    required this.data, // here in constructor
  }) : super(key: key);

  final Data data; // final variable

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

class _MyAppState extends State<MyMaps> {
  late GoogleMapController mapController;

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    final data = widget.data; // get the data that comes 

    debugPrint(data.toString());

    LatLng _center = LatLng(
      data.coordx,
      data.coordy,
    ); // voila !

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Maps Sample App'),
          backgroundColor: Colors.green[700],
        ),
        body: GoogleMap(
          onMapCreated: _onMapCreated,
          initialCameraPosition: CameraPosition(
            target: _center,
            zoom: 11.0,
          ),
        ),
      ),
    );
  }
}

要支持null,需要转换

final data = ModalRoute.of(context)!.settings.arguments as Data;

 final data = ModalRoute.of(context)!.settings.arguments as Data?;