Flutter integration_test:无法向 tester.enterText() 方法输入整数、双精度值?

Flutter integration_test: Can't input integer, double values to tester.enterText() method?

我正在为我的 flutter-web 应用程序开发 integration_test ....其中我遇到 tester.enterText() 方法不输入整数,双精度值,因为它的数据类型仅限于字符串类型.如果我的 TextField 只接受数字并且 keyboardType 属性 设置为 keyboardType: TextInputType.number 怎么办?

尝试将其类型转换为字符串类型,但结果 TextField 不接受任何非字符串值。 以下测试用例失败,出现以下异常: 应为 String 类型的值,但得到了 int

类型的值

可重现样本:

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _scaleTextController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        alignment: Alignment.center,
        child: TextFormField(
          controller: _scaleTextController,
          inputFormatters: [
            FilteringTextInputFormatter.allow(
              RegExp(r'^\d*\.?\d{0,6}'),
            ),
          ],
          keyboardType: TextInputType.number,
          autofocus: true,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:hello_world/main.dart' as app;

void main() async {
  group('Complete E2E Test', () {
    IntegrationTestWidgetsFlutterBinding.ensureInitialized();

    setUp(() {
      app.main();
    });

    testWidgets('Hello World test', (WidgetTester tester) async {
      final inputField = find.byType(TextField).first;
      await tester.tap(inputField);
      await tester.enterText(inputField, 2 as String);
    });
  });
}

只需使用 toString() 而不是转换

比如

假设你有一个 int 变量

int x = 2;

要将其更改为字符串,只需使用

x.toString();