Ad

Flutter Integration_test: Can't Input Integer, Double Values To Tester.enterText() Method?

I am developing integration_test for my flutter-web application ....wherein I encountered tester.enterText() method doesn't input integer, double value as its restricted its data type to only String type. What if my TextField accepts only numbers and keyboardType property set to keyboardType: TextInputType.number?

Tried type casting it to String type but resulting TextField wont accept any non-string value. Below test case fails with below exception: Expected a value of type String, but got one of type int

Reproducible sample:

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);
    });
  });
}
Ad

Answer

Just use toString() instead of casting

such as

let's say you have a int variable

int x = 2;

To change it to a string, just use

x.toString();
Ad
source: stackoverflow.com
Ad