简体   繁体   中英

Dart regular expression error Try calling using?

I have

Error: Method 'group' cannot be called on 'RegExpMatch?' because it is potentially null.

 - 'RegExpMatch' is from 'dart:core'.

Try calling using ?. instead.

                final everything = match.group(0);

And my source code is here below, just a simple Regular expression.

Where should I fix this??

RegExp regExp = new RegExp(r'[0-9][0-9]');

RegExpMatch match = regExp.firstMatch(results.text);
         
final everything = match.group(0);

I changed the source code like this

  RegExp regExp = new RegExp(r'C(S|N)-[0-9][0-9][0-9]-[0-9][0-9][0-9]');

  if (regExp.hasMatch(results.text)){
     
        RegExpMatch match = regExp.firstMatch(results.text);
         
        final everything = match!.group(0);
        _showMyDialog(everything);
          
  }

Still error happens.

lib/camera_preview_scanner.dart:77:44: Error: A value of type 'RegExpMatch?' can't be assigned to a variable of type 'RegExpMatch' because 'RegExpMatch?' is nullable and 'RegExpMatch' isn't.

 - 'RegExpMatch' is from 'dart:core'.

                RegExpMatch match = regExp.firstMatch(results.text);

                                           ^

lib/camera_preview_scanner.dart:79:36: Warning: Operand of null-aware operation '!' has type 'RegExpMatch' which excludes null.

 - 'RegExpMatch' is from 'dart:core'.

                final everything = match!.group(0);

Solution

use RegExp! instead of RegExp

  RegExp! regExp = new RegExp(r'C(S|N)-[0-9][0-9][0-9]-[0-9][0-9][0-9]');

  if (regExp.hasMatch(results.text)){
     
        RegExpMatch match = regExp.firstMatch(results.text);
         
        final everything = match!.group(0);
        _showMyDialog(everything);
          
  }

Do

final everything = match!.group(0);

or better

if(match != null){ 
   final everything = match!.group(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM