Flutter web 开发中会碰到很多问题,本文介绍 Flutter web 如何获取Url参数以及解决获取Url参数可能存在为空的问题。

从Url获取参数

1
2
3
4
5
void main(){
  var url = Uri.base.toString();
  var uuid = url.queryParameters['uuid'];
  var token = url.queryParameters['token'];
}

必须在main方法中获取,如果是在页面获取可能会被跳转刷新。获取后传递给App()。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void main() {
  var url = Uri.base.toString();
  var uuid = Uri.base.queryParameters['uuid'];
  var token = Uri.base.queryParameters['token'];
  print('url:$url}\nuuid:$uuid\ntoken:$token');
  runApp(MyApp(
    url: url,
    uuid: uuid,
    token: token,
  ));
}

可能碰到的获取参数为空

当你的url是http://localhost:50053/?uuid=1234&token=4321可以正确获取。 但是 如果你的url为http://localhost:50053/#/?uuid=1234&token=4321时,上述代码获取的uuid和token参数为null,引起这个问题的原因是url中含有#字符,替换掉这个#字符,即可正确获取参数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
void main() {
  var url = Uri.base.toString();
  var uuid = Uri.base.queryParameters['uuid'];
  var token = Uri.base.queryParameters['token'];
  runApp(MyApp(
    url: url,
    uuid: uuid,
    token: token,
  ));
}

改为

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void main() {
  var url = Uri.base.toString();
  var uri = Uri.parse(url.replaceFirst('#/', ''));
  var uuid = uri.queryParameters['uuid'];
  var token = uri.queryParameters['token'];
  runApp(MyApp(
    url: url,
    uuid: uuid,
    token: token,
  ));
}

完整代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import 'package:flutter/material.dart';

void main() {
  var url = Uri.base.toString();
  var uri = Uri.parse(url.replaceFirst('#/', ''));
  var uuid = uri.queryParameters['uuid'];
  var token = uri.queryParameters['token'];
  runApp(MyApp(
    url: url,
    uuid: uuid,
    token: token,
  ));
}

class MyApp extends StatelessWidget {
  final String url;
  final String? uuid;
  final String? token;

  const MyApp({super.key, required this.url, this.uuid, this.token});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Web Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('获取Url参数'),
        ),
        body: Container(
          padding: const EdgeInsets.all(20),
          alignment: Alignment.center,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text('url:$url'),
              Text('uuid:$uuid'),
              Text('token:$token')
            ],
          ),
        ),
      ),
    );
  }
}

demo效果

flutter-web-get-url-parameters-demo