flutter 中使用 WebView加载H5页面异常net:ERR_CLEARTEXT_NOT_PERMITTED

最近有个flutter项目中根据搜索结果跳转到相应的H5页面发现老是报错,曾现在闲暇拉出来解决哈

先来看一个搜索功能的测试

已进入详情页面就提示错误,尴尬了。

只有去检测代码了撒

Search.dart


    SearchItem item = searchModel.data[position];
    print(item.url);
    return GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => WebView(
                      url: item.url,
                      title: '详情',
                    )));
      },
      

检测该处并无问题,于是继续向上查找,找到了Search_model.dart


	class SearchModel{
	  String keyword;
	  final List<SearchItem> data;
	  SearchModel({this.data});
	  factory SearchModel.fromJson(Map<String,dynamic>json){
	    var dataJson = json['data'] as List;
	    List<SearchItem> data = dataJson.map((i)=>SearchItem.fromJson(i)).toList();
	    return SearchModel(data:data);
	  }
	}

确认该处也没问题,那么问题可能是json格式化类SearchItem

class SearchItem


	class SearchItem{
	  final String word;  //xx酒店
	  final String type;  //hotel
	  final String price ;  //实时计价
	  final String star ;  //豪华型
	  final String zonename ; //虹桥
	  final String districtname ; //上海
	  final String url ;
	
	
	  SearchItem({this.word, this.type, this.price, this.star, this.zonename,
	    this.districtname, this.url});
	
	  factory SearchItem.fromJson(Map<String,dynamic>json){
	    return SearchItem(
	        word: json['word'],
	        type: json['type'],
	        price: json['price'],
	        star: json['star'],
	        zonename: json['zonename'],
	        districtname:json['districtname'],
	        url:json['url']
	    );
	  }
	
	  Map<String, dynamic> toJson(){
	    Map<String,dynamic> data = new Map<String,dynamic>();
	    data['icon'] = this.word;
	    data['title'] = this.type;
	    data['price'] = this.price;
	    data['star'] = this.star;
	    data['zonename'] = this.zonename;
	    data['districtname'] = this.districtname;
	    data['url'] = this.url;
	
	    return data;
	  }
	}
	

打眼看去是否也没什么问题呀,那为是么无法进入详情页面呢,经过再次阅读代码发现toJson方法好像并无用处(这个好像是上次测试
Text(object)渲染对象,需要进行序列化时留下的)

于是果断干掉,再测试(当初断定是这个引起的因为我删除这个方法测试过一次OK了)

但是事实并非想象的那么简单(gradle.propertiesbuild.gradledependencies都改了一遍–抓狂),再次测试依然一样报错

最后一次次找,才发现实从Android 9.0(API级别28)开始,默认情况下禁用明文支持。因此http的url均无法在webview中加载

解决方法:在AndroidManifest.xmlapplaction节点中添加android:usesCleartextTraffic="true" 即可(害我找了半天)

如:


    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="flutter_test"
        android:usesCleartextTraffic="true"
        android:icon="@mipmap/ic_launcher">
		<!-- ... another configure -->
	</application>
	

另外如果是ios 则在 info.plist中增加


 <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    

再测试哈


总算OK了,特此记录,避免再入坑

发布了101 篇原创文章 · 获赞 13 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_34817440/article/details/104115158